#include "CThreadLocalObject.h"

BYTE __afxThreadData[sizeof(CThreadSlotData)];
CThreadSlotData* _afxThreadData;

CThreadLocalObject::~CThreadLocalObject()
{
    if ((m_nSlot != 0) && (_afxThreadData != NULL))
    {
        _afxThreadData->FreeSlot(m_nSlot);
    }

    m_nSlot = 0;
}

#pragma warning (disable : 4291)
CNoTrackObject* CThreadLocalObject::GetData(CNoTrackObject* (__stdcall* pfnCreateObject)())
{
    if (m_nSlot == 0)
    {
        if (!_afxThreadData)
        {
            _afxThreadData = new (__afxThreadData)CThreadSlotData;
            m_nSlot = _afxThreadData->AllocSlot();
        }
    }

    CNoTrackObject* pValue = (CNoTrackObject*)_afxThreadData->GetThreadValue(m_nSlot);
    if (!pValue)
    {
        pValue = (*pfnCreateObject)();
        _afxThreadData->SetValue(m_nSlot, pValue);
    }

    return pValue;
}

CNoTrackObject* CThreadLocalObject::GetDataNA()
{
    if (m_nSlot == 0 || _afxThreadData == 0) return NULL;

    return (CNoTrackObject*)_afxThreadData->GetThreadValue(m_nSlot);
}
